define(['text!tweet/tweet-issue.html', "../base/openapi", '../base/util', '../base/login/login', '../base/caretInsert/zepto.caretInsert', ],
	function(viewTemplate, OpenAPI, Util, Login) {
		return Piece.View.extend({
			id: 'tweet_tweet-issue',
			login: null,
			uploadImageUrl: "",
			offset: 0,
			events: {
				"click .emotion": "ins_e",
				"click #showEmotion": "showEmotion",
				"click #insertSoftName": "insertSoftName",
				"click #insertUserName": "insertUserName",
				"click .backBtn": "goBack",
				"click .issueTweet": "tweetIssue",
				// "keydown .issueTextarea": "countNum",
				"click .countTween": "clearTweet",
				"click #getPicture": "showChooseOption",
				"focus #issueTextarea": "focusCom"
			},
			//simona--modify--textarea获得焦点的时间表情收起
			focusCom: function() {
				var dataSign = $("#showEmotion").attr("data-sign");
				if (dataSign === "down") {
					this.showEmotion();
				}
			},
			showChooseOption: function() {
				//收起表情
				var dataSign = $("#showEmotion").attr("data-sign");
				if (dataSign === "down") {
					this.showEmotion();
				}

				var me = this;
				var dialog = new Piece.Dialog({
					autoshow: true,
					target: 'body',
					title: '请选择',
					content: ''
				}, {
					configs: [{
						title: "手机拍照",
						eventName: 'camera'
					}, {
						title: "手机相册",
						eventName: 'library'
					}],
					camera: function() {
						me.getPicture("CAMERA");
						// dialog.hide();
					},
					library: function() {
						me.getPicture("PHOTOLIBRARY");
						// dialog.hide();
					}
				});
				$('.cube-dialog-screen').click(function(){
					dialog.hide();
				})
			},
			getPicture: function(type) {
				var me = this;

				var pictureSource = navigator.camera.PictureSourceType;
				var destinationType = navigator.camera.DestinationType;

				function onSuccess(imageUrl) {
					me.uploadImageUrl = imageUrl;
					$('#uploadImage').attr("src", imageUrl);
					$('#uploadImage').attr("data-src", imageUrl);
					$("#uploadImage").show();
				}

				function onFail(message) {
					// alert('Failed because: ' + message);
				}
				var source;
				if (type === "CAMERA") {
					source = pictureSource.CAMERA;
				} else {
					source = pictureSource.PHOTOLIBRARY;
				}
				// var source = pictureSource.CAMERA;
				navigator.camera.getPicture(onSuccess, onFail, {
					quality: 75,
					allowEdit: true,
					encodingType: Camera.EncodingType.JPEG,
					destinationType: destinationType.FILE_URI,
					sourceType: source
				});
			},
			tweetPub: function() {
				var me = this;
				var issueCont = $(".issueTextarea").val();
				issueCont = issueCont.replace(/(\s*$)/g, "");
		
				if (issueCont === "" || issueCont === " ") {
					new Piece.Toast('请输入动弹内容');
				} else {
					//Util.Ajax();
					var me = this;
					var user_token = Piece.Store.loadObject("user_token");
					var access_token = user_token.access_token;
					//如果没有选择图片，则用ajax上传。
					if ($("#uploadImage").attr("data-src") === null) {
						Util.Ajax(OpenAPI.tweet_pub, "GET", {
							access_token: access_token,
							msg: issueCont,
							"dataType": "jsonp"
						}, 'json', function(data, textStatus, jqXHR) {
							if (data.error === "200") {
								//alert("发布成功");
								new Piece.Toast('发布成功');
								setTimeout(function() {
									history.back();
								}, 1500);
							} else {
								new Piece.Toast(data.error_description)
							}
						}, null, null);
					} else {
						//如果选择图片，则用phonegap插件上传。
						me.uploadPhoto(me.uploadImageUrl, access_token, issueCont);
					}
				}
			},

			uploadPhoto: function(imageURI, access_token, issueCont) {

				var loader = new Piece.Loader({
					autoshow: true, //是否初始化时就弹出加载控件
					target: 'body' //页面目标组件表识
				});

				function win(r) {
					console.log("Code = " + r.responseCode);
					console.log("Response = " + r.response);
					console.log("Sent = " + r.bytesSent);
					var response = JSON.parse(r.response);
					if (response.error === "200") {
						new Piece.Toast('发布成功');
						setTimeout(function() {
							history.back();
						}, 1500);
					} else {
						new Piece.Toast('发布失败,请检查填写信息,重试');
					}

					loader.hide();
				};

				function fail(error) {
					loader.hide();
					new Piece.Toast('发布失败,请检查填写信息,重试');
					// alert("An error has occurred: Code = " + error.code);
					console.log("upload error source " + error.source);
					console.log("upload error target " + error.target);
				};

				console.info("=============" + imageURI);
				var options = new FileUploadOptions();
				options.fileKey = "img";
				options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1) + ".jpg";
				options.mimeType = "image/jpeg";
				var params = {};
				params.access_token = access_token;
				params.msg = issueCont;
				options.params = params;
				var ft = new FileTransfer();
				ft.upload(imageURI, encodeURI(OpenAPI.tweet_pub), win, fail, options);
			},
			ins_e: function(el) {
				$target = $(el.currentTarget);
				var num = $target.attr("data-num");
				$("#issueTextarea").insertContent(num);
				this.countNum();
			},
			showEmotion: function() {
				$("#TweetEmotions").toggle();
				var dataSign = $("#showEmotion").attr("data-sign");
				if (dataSign === "up") {
					$(".countTween").attr({
						"style":"bottom:230px;"
					});
					$(".bar-tab").attr({
						"style": "position:fixed;bottom:170px;"
					});
					$("#showEmotion").attr({
						"data-sign": "down"
					});
					var myScroll = new iScroll("TweetEmotions",{
					checkDOMChanges: true
				});

				} else {
					$(".countTween").attr({
						"style":"bottom:60px;"
					});
					$(".bar-tab").attr({
						"style": "none"
					});
					$("#showEmotion").attr({
						"data-sign": "up"
					});
					// $("issueTextarea").blur();
				}
				//记录光标的位置

				// var soffset = $("#issueTextarea").getOffset();


			},
			insertSoftName: function() {
				$(".issueTextarea").insertContent("#请输入软件名#", 1, -1);
				this.countNum();
			},
			insertUserName: function() {
				$(".issueTextarea").insertContent("@请输入用户名", 1, 0);
				this.countNum();
			},
			goBack: function() {
				history.back();
			},
			tweetIssue: function() {
				Util.checkLogin();
				var checkLogin = Util.checkLogin();
				if (checkLogin === false) {
					login.show();
				} else {
					this.tweetPub();
				}
			},
			countNum: function() {
				var me = this;
				var tweetCont = $(me.el).find("#issueTextarea").val();
				var contLen = tweetCont.length; //用户输入文本的长度
		
				if (contLen >= 160) {
					tweetCont = tweetCont.substring(0, 160);
					$(me.el).find("#issueTextarea").val(tweetCont);
					$(me.el).find("#allowNum").html(0);
					new Piece.Toast('您输入的字数已达到160个');
				} else {
					$(me.el).find("#allowNum").html(160 - contLen);
				}
		

			},
			clearTweet: function() {
				var issueCont = $(".issueTextarea").val();
				issueCont = issueCont.replace(/(\s*$)/g, ""); //去掉右边空格
				if (issueCont !== "" && issueCont !== " ") {
					var that = this;
					var dialog = new Piece.Dialog({
						autoshow: false,
						target: 'body',
						title: '清除文字吗？',
						content: ''
					}, {
						configs: [{
							title: '确认',
							eventName: 'ok'
						}, {
							title: '取消',
						}],
						ok: function() {
							$("#issueTextarea").val("");
							that.countNum();
						}
					});

					dialog.show();
				}

			},
			render: function() {
				login = new Login();
				$(this.el).html(viewTemplate);

				Piece.View.prototype.render.call(this);
				return this;
			},
			onShow: function() {

				$(".issueTextarea").focus();
				var me = this;
				$(this.el).find(".issueTextarea").bind("input propertychange", function() {
					me.countNum();

				});
				var userOp = Util.request("userOp");
				userOp = decodeURI(decodeURI(userOp));
				if (userOp) {
					$(".issueTextarea").val(userOp+" ");
				}
				me.countNum();
				var emotions = new Array();
				for (var i = 1; i <= 105; i++) {
					var emotion = {};
					// emotion.num = "[" + i + "]";
					//----simona--modify--
					if (i === 66 || i === 102) {
						continue;
					}
					var num = "";

					if (i < 10) {
						num = "00" + i;
					} else if (i >= 10 && i < 100) {
						num = "0" + i;
					} else {
						num = i;
					}
					emotion.alias = num;
					// console.info(alias)
					emotion.num = "[" + (i - 1) + "]";
					emotion.position = -24 * i;
					emotions.push(emotion);
				}
				var data = {
					"emotions": emotions
				};
				var emotionsTemplate = $(this.el).find("#emotionsTemplate").html();
				var emotionsHtml = _.template(emotionsTemplate, data);
				$("#TweetEmotions").html("");
				$("#TweetEmotions").append(emotionsHtml);


				
			},
			showkeyboard:function(){
				var availHeight = window.screen.availHeight ;
				if(availHeight<230){
					$('.issueTextarea').css("margin-top","20px")
				}
				if(availHeight>230){
					$('.issueTextarea').css("margin-top","0px")
				}
			}
		}); //view define

	});